package com.maotouying.owlsmart.moviePage;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.maotouying.owlsmart.R;
import com.maotouying.owlsmart.SmartUtil.SystemUtil;
import com.maotouying.owlsmart.moviePage.List.HorizontalListView;
import com.maotouying.owlsmart.moviePage.List.dramaSeries_A;
import com.maotouying.owlsmart.moviePage.List.dramaSeries_C;
import com.yc.kernel.factory.PlayerFactory;
import com.yc.kernel.utils.PlayerConstant;
import com.yc.kernel.utils.PlayerFactoryUtils;
import com.yc.video.config.ConstantKeys;
import com.yc.video.config.VideoPlayerConfig;
import com.yc.video.player.OnVideoStateListener;
import com.yc.video.player.VideoPlayer;
import com.yc.video.player.VideoPlayerBuilder;
import com.yc.video.player.VideoViewManager;
import com.yc.video.ui.view.BasisVideoController;
import com.yc.video.ui.view.CustomErrorView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class moviePalyerActivity extends AppCompatActivity {

    private VideoPlayer mVideoPlayer;

    private BasisVideoController controller;

    private smartViewPager viewPager;

    private View palyerDetail, palyerDiscuss;

    private List<View> viewlist;

    private Button btn_detail, btn_discuss;

    private TextView tv_detail;
    private ImageView iv_detail;

    private TextView tv_player_title, tv_player_time;
    private LinearLayout ll_list;

   private String videourl = "";
    private String videobg = "";
    private String filePhp="msearchdetail.php";

    private LinearLayout dram_hint;

    private dramaSeries_C dramaSeries_c;
    private List<dramaSeries_C> dramaSeries_cs= new ArrayList<dramaSeries_C>();
    private HorizontalListView hlv;
    private dramaSeries_A dramaSeries_a;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_palyer);
        //顶部框颜色
        SystemUtil.setStatusBarColor(this, this.getResources().getColor(R.color.top_background_color));

        //滑动导航
        viewPager = (smartViewPager) findViewById(R.id.viewPager);
        btn_discuss = (Button) findViewById(R.id.btn_discuss);
        btn_detail = (Button) findViewById(R.id.btn_detail);

        //播放器初始化要用的
        initFindViewById();


        //初始化滑动导航
        initView();
        //初始化详情view
        initDetail();


        //拿到返回的参数
        Intent intent = getIntent();
        String Activity = intent.getStringExtra("Activity");
        String vod_id = intent.getStringExtra("vod_id");
//tsearchdetail.php
        if(Activity.equals("movieListActivity")){

            filePhp="msearchdetail.php";
        }else if(Activity.equals("tvListActivity")){
            filePhp="tsearchdetail.php";
        }



        //获取影片所有参数

        okhttp_text(vod_id);

        //调用播放器
        initVideoPlayer();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mVideoPlayer != null) {
            //从后台切换到前台，当视频暂停时或者缓冲暂停时，调用该方法重新开启视频播放
            mVideoPlayer.resume();
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mVideoPlayer != null) {
            //从前台切到后台，当视频正在播放或者正在缓冲时，调用该方法暂停视频
            mVideoPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mVideoPlayer != null) {
            //销毁页面，释放，内部的播放器被释放掉，同时如果在全屏、小窗口模式下都会退出
            mVideoPlayer.release();
        }
    }

    @Override
    public void onBackPressed() {
        //处理返回键逻辑；如果是全屏，则退出全屏；如果是小窗口，则退出小窗口
        if (mVideoPlayer == null || !mVideoPlayer.onBackPressed()) {
            super.onBackPressed();
        }
    }

    private void initFindViewById() {
        mVideoPlayer = findViewById(R.id.video_player);

    }

    private void initVideoPlayer() {

        if (videourl == null || videourl.length() == 0) {
            videourl = "";
        }
        //创建基础视频播放器，一般播放器的功能
        controller = new BasisVideoController(this);
        //设置控制器
        mVideoPlayer.setController(controller);
        //设置视频播放链接地址
        mVideoPlayer.setUrl(videourl);
        //开始播放
       mVideoPlayer.start();
//重新播放
       // mVideoPlayer.replay(true);
        mVideoPlayer.postDelayed(new Runnable() {
            @Override
            public void run() {
                mVideoPlayer.start();
            }
        }, 300);
        //设置视频背景图
        Glide.with(this).load(videobg).into(controller.getThumb());
    }

    //滑动用的布局
    private void initView() {
        //获取布局文件
        LayoutInflater inflater = getLayoutInflater();
        palyerDetail = inflater.inflate(R.layout.palyer_detail, null);
        palyerDiscuss = inflater.inflate(R.layout.palyer_discuss, null);
        //将三个View添加进viewlist数组
        viewlist = new ArrayList<View>();
        viewlist.add(palyerDetail);
        viewlist.add(palyerDiscuss);
        //设置适配器
        PagerAdapter pagerAdapter = new PagerAdapter() {
            //适配器必须有一下四个方法
            //返回界面数量
            public int getCount() {
                return viewlist.size();
            }

            //判断view和o的对应关系，instantiateItem返回view
            public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
                return view == o;
            }

            //移除当前界面
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewlist.get(position));
            }

            //添加界面至当前，并返回当前界面
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                container.addView(viewlist.get(position));
                return viewlist.get(position);
            }
        };
        //绑定适配器
        viewPager.setAdapter(pagerAdapter);
        //设置viewPager的初始界面为第一个界面
        viewPager.setCurrentItem(0);
        //添加切换界面的监听器
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                if (position == 0) {
                    btn_detail.setTextColor(Color.parseColor("#00B2EE"));
                    btn_discuss.setTextColor(Color.parseColor("#696969"));
                } else if (position == 1) {
                    btn_discuss.setTextColor(Color.parseColor("#00B2EE"));
                    btn_detail.setTextColor(Color.parseColor("#696969"));
                }

            }

            @Override
            public void onPageSelected(int position) {


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    //播放器测试与调试的接口
    private void test() {
        //VideoPlayer相关
        VideoPlayerBuilder.Builder builder = VideoPlayerBuilder.newBuilder();
        VideoPlayerBuilder videoPlayerBuilder = new VideoPlayerBuilder(builder);
        //设置视频播放器的背景色
        builder.setPlayerBackgroundColor(Color.BLACK);
        //设置小屏的宽高
        int[] mTinyScreenSize = {0, 0};
        builder.setTinyScreenSize(mTinyScreenSize);
        //是否开启AudioFocus监听， 默认开启
        builder.setEnableAudioFocus(false);
        mVideoPlayer.setVideoBuilder(videoPlayerBuilder);
        //截图
        Bitmap bitmap = mVideoPlayer.doScreenShot();
        //移除所有播放状态监听
        mVideoPlayer.clearOnStateChangeListeners();
        //获取当前缓冲百分比
        int bufferedPercentage = mVideoPlayer.getBufferedPercentage();
        //获取当前播放器的状态
        int currentPlayerState = mVideoPlayer.getCurrentPlayerState();
        //获取当前的播放状态
        int currentPlayState = mVideoPlayer.getCurrentPlayState();
        //获取当前播放的位置
        long currentPosition = mVideoPlayer.getCurrentPosition();
        //获取视频总时长
        long duration = mVideoPlayer.getDuration();
        //获取倍速速度
        float speed = mVideoPlayer.getSpeed();
        //获取缓冲速度
        long tcpSpeed = mVideoPlayer.getTcpSpeed();
        //获取视频宽高
        int[] videoSize = mVideoPlayer.getVideoSize();
        //是否处于静音状态
        boolean mute = mVideoPlayer.isMute();
        //判断是否处于全屏状态
        boolean fullScreen = mVideoPlayer.isFullScreen();
        //是否是小窗口模式
        boolean tinyScreen = mVideoPlayer.isTinyScreen();

        //是否处于播放状态
        boolean playing = mVideoPlayer.isPlaying();
        //暂停播放
        mVideoPlayer.pause();
        //视频缓冲完毕，准备开始播放时回调
        mVideoPlayer.onPrepared();
        //重新播放
        mVideoPlayer.replay(true);
        //继续播放
        mVideoPlayer.resume();
        //调整播放进度
        mVideoPlayer.seekTo(100);
        //循环播放， 默认不循环播放
        mVideoPlayer.setLooping(true);
        //设置播放速度
        mVideoPlayer.setSpeed(1.1f);
        //设置音量 0.0f-1.0f 之间
        mVideoPlayer.setVolume(1, 1);
        //开始播放
        mVideoPlayer.start();


        //进入全屏
        mVideoPlayer.startFullScreen();
        //退出全屏
        mVideoPlayer.stopFullScreen();
        //开启小屏
        mVideoPlayer.startTinyScreen();
        //退出小屏
        mVideoPlayer.stopTinyScreen();

        mVideoPlayer.setOnStateChangeListener(new OnVideoStateListener() {
            /**
             * 播放模式
             * 普通模式，小窗口模式，正常模式三种其中一种
             * MODE_NORMAL              普通模式
             * MODE_FULL_SCREEN         全屏模式
             * MODE_TINY_WINDOW         小屏模式
             * @param playerState                       播放模式
             */
            @Override
            public void onPlayerStateChanged(int playerState) {
                switch (playerState) {
                    case ConstantKeys.PlayMode.MODE_NORMAL:
                        //普通模式
                        break;
                    case ConstantKeys.PlayMode.MODE_FULL_SCREEN:
                        //全屏模式
                        break;
                    case ConstantKeys.PlayMode.MODE_TINY_WINDOW:
                        //小屏模式
                        break;
                }
            }

            /**
             * 播放状态
             * -1               播放错误
             * 0                播放未开始
             * 1                播放准备中
             * 2                播放准备就绪
             * 3                正在播放
             * 4                暂停播放
             * 5                正在缓冲(播放器正在播放时，缓冲区数据不足，进行缓冲，缓冲区数据足够后恢复播放)
             * 6                暂停缓冲(播放器正在播放时，缓冲区数据不足，进行缓冲，此时暂停播放器，继续缓冲，缓冲区数据足够后恢复暂停
             * 7                播放完成
             * 8                开始播放中止
             * @param playState                         播放状态，主要是指播放器的各种状态
             */
            @Override
            public void onPlayStateChanged(int playState) {
                switch (playState) {
                    case ConstantKeys.CurrentState.STATE_IDLE:
                        //播放未开始，初始化
                        break;
                    case ConstantKeys.CurrentState.STATE_START_ABORT:
                        //开始播放中止
                        break;
                    case ConstantKeys.CurrentState.STATE_PREPARING:
                        //播放准备中
                        break;
                    case ConstantKeys.CurrentState.STATE_PREPARED:
                        //播放准备就绪
                        break;
                    case ConstantKeys.CurrentState.STATE_ERROR:
                        //播放错误
                        break;
                    case ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING:
                        //正在缓冲
                        break;
                    case ConstantKeys.CurrentState.STATE_PLAYING:
                        //正在播放
                        break;
                    case ConstantKeys.CurrentState.STATE_PAUSED:
                        //暂停播放
                        break;
                    case ConstantKeys.CurrentState.STATE_BUFFERING_PAUSED:
                        //暂停缓冲
                        break;
                    case ConstantKeys.CurrentState.STATE_COMPLETED:
                        //播放完成
                        break;
                }
            }
        });

        //设置视频背景图
        ImageView thumb = controller.getThumb();
        Glide.with(this).load(R.drawable.ic_clipimage).into(controller.getThumb());
        //设置视频标题
        controller.setTitle("视频标题");
        //添加自定义视图。每添加一个视图，都是方式层级树的最上层
        CustomErrorView customErrorView = new CustomErrorView(this);
        controller.addControlComponent(customErrorView);
        //移除控制组件
        controller.removeControlComponent(customErrorView);
        //移除所有的组件
        controller.removeAllControlComponent();
        //隐藏播放视图
        controller.hide();
        //显示播放视图
        controller.show();
        //是否开启根据屏幕方向进入/退出全屏
        controller.setEnableOrientation(true);
        //显示移动网络播放提示
        controller.showNetWarning();
        //刘海的高度
        int cutoutHeight = controller.getCutoutHeight();
        //是否有刘海屏
        boolean b = controller.hasCutout();
        //设置是否适配刘海屏
        controller.setAdaptCutout(true);
        //停止刷新进度
        controller.stopProgress();
        //开始刷新进度，注意：需在STATE_PLAYING时调用才会开始刷新进度
        controller.startProgress();
        //判断是否锁屏
        boolean locked = controller.isLocked();
        //设置是否锁屏
        controller.setLocked(true);
        //取消计时
        controller.stopFadeOut();
        //开始计时
        controller.startFadeOut();
        //设置播放视图自动隐藏超时
        controller.setDismissTimeout(8);
        //销毁
        controller.destroy();


        //播放器配置，注意：此为全局配置，按需开启
        PlayerFactory player = PlayerFactoryUtils.getPlayer(PlayerConstant.PlayerType.TYPE_IJK);
        VideoViewManager.setConfig(VideoPlayerConfig.newBuilder()
                //设置上下文
                .setContext(this)
                //设置视频全局埋点事件
                //.setBuriedPointEvent(new BuriedPointEventImpl())
                //调试的时候请打开日志，方便排错
                .setLogEnabled(true)
                //设置ijk
                .setPlayerFactory(player)
                //在移动环境下调用start()后是否继续播放，默认不继续播放
                .setPlayOnMobileNetwork(false)
                //是否开启AudioFocus监听， 默认开启
                .setEnableAudioFocus(true)
                //是否适配刘海屏，默认适配
                .setAdaptCutout(true)
                //监听设备方向来切换全屏/半屏， 默认不开启
                .setEnableOrientation(false)
                //设置自定义渲染view，自定义RenderView
                //.setRenderViewFactory(null)
                //创建
                .build());

    }


    //获取数据的
    public void okhttp_text(String search) {


        //创建okHttpclient的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建Request,Builder
        Request.Builder builder = new Request.Builder();
        //使用Request.Builder对象,调用Url方法,传入网路路径
        Request.Builder url = builder.url("http://103.45.145.67/testfolder/"+filePhp+"?movie_id=" + search);
        //使用Request.Builder对象,调用builder方法构件request对象
        Request request = url.build();
        //创建一个Call对象,参数就request对象
        Call call = okHttpClient.newCall(request);
        //使用call对象,调用enqueue方法,请求加入调度(异步加载)

        call.enqueue(new Callback() {
            //当请求失败的时候,调用此方法
            @Override
            public void onFailure(Call call, IOException e) {
                //andler.sendEmptyMessage(FALL);
            }

            //当请求成功的时候,调用此方法
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String source = response.body().string();
                //System.out.println(source);

                //去除括号直接读

                String result1 = source.replace("[", "");
                String result = result1.replace("]", "");

                JSONObject data_key = JSONObject.parseObject(result);
                String vod_name = data_key.getString("vod_name");//标题单独一个
                String vod_class = data_key.getString("vod_class");
                String vod_author = data_key.getString("vod_author");
                String vod_director = data_key.getString("vod_director");
                String vod_blurb = data_key.getString("vod_blurb");
                String vod_area = data_key.getString("vod_area");
                String vod_lang = data_key.getString("vod_lang");

                String vod_year = data_key.getString("vod_year");
                String vod_score = data_key.getString("vod_score");
                String vod_add_time = data_key.getString("vod_add_time");//单独一个
                String vod_pic = data_key.getString("vod_pic");

                String vod_play_url = data_key.getString("vod_play_url");

                String listData = vod_class + "," + vod_area + "," + vod_lang + "," + vod_year + "," + vod_score;
                String introData =  "导演：" + vod_director +"\n主演：" + vod_author + "\n剧情简介：" + vod_blurb;

                Message msg = new Message();
                msg.what = 21;

                Bundle bundle = new Bundle();
                bundle.putString("vod_name", vod_name);//片名
                bundle.putString("vod_add_time", vod_add_time);//上架时间
                bundle.putString("vod_pic", vod_pic);//图片地址
                bundle.putString("listData", listData);//视频地址
                bundle.putString("introData", introData);//简介
                bundle.putString("vod_play_url", vod_play_url);//视频地址
                msg.setData(bundle);
                Thandler.sendMessage(msg);//用activity中的handler发送消息
            }
        });
    }

    private Handler Thandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 21:
                    String vod_name = msg.getData().getString("vod_name");
                    String vod_add_time = msg.getData().getString("vod_add_time");
                    String listData = msg.getData().getString("listData");
                    String introData = msg.getData().getString("introData");
                    String vod_play_url = msg.getData().getString("vod_play_url");
                    String vod_pic = msg.getData().getString("vod_pic");
                    tv_player_title.setText(vod_name);
                    tv_detail.setText(introData);
                    tv_player_time.setText(vod_add_time);

                    String ld[] =  listData.split(",");
                    for (int i=0;i<5;i++){
                        TextView tvd = new TextView(moviePalyerActivity.this);
                        tvd.setText(ld[i]);
                        tvd.setMarqueeRepeatLimit(1);
                        tvd.setBackground(tvd.getContext().getDrawable( R.drawable.player_list_item));
                        tvd.setGravity(Gravity.CENTER);
                        tvd.setPadding(50,10,50,10);
                        ll_list.addView(tvd);
                    }

                    System.out.println(vod_play_url);


                    videobg = vod_pic;
                    videourl= playerurl(vod_play_url);
                    initVideoPlayer();
                    break;

                case 31:
                    dramaSeries_cs.clear();
                    String splitUrl = msg.getData().getString("vod_play_url");
                    String[] str = splitUrl.split("#");
                    for(int i=0;i<str.length;i++){


                        //episode,playerurl
                        String std[]= str[i].split("\\$");

                        dramaSeries_c = new dramaSeries_C();
                        dramaSeries_c.setEpisode(std[0]);
                        dramaSeries_c.setPlayerurl(std[1]);

                        System.out.println(std[0]);
                        System.out.println(std[1]);

                        dramaSeries_cs.add(dramaSeries_c);

                    }
                    clickData((ArrayList<dramaSeries_C>) dramaSeries_cs);
                    break;

            }
        }
    };

    public void clickData(ArrayList<dramaSeries_C> dramaSeries_cs) {

        dramaSeries_a = new dramaSeries_A(R.layout.item_dramaseries, moviePalyerActivity.this, dramaSeries_cs);


        hlv.setAdapter(dramaSeries_a);
        hlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                final TextView episode = (TextView) view.findViewById(R.id.episode);//id
                final TextView playerurl = (TextView) view.findViewById(R.id.playerurl);//id

                videourl= playerurl.getText().toString();
                initVideoPlayer();
                mVideoPlayer.replay(true);
            }
        });


    }


    private String playerurl(String vod_play_url){
       // HD高清$https://youku.cdn-2-okzy.com/20181228/20645_c7208d65/index.m3u8
        String url[] = vod_play_url.split("\\$");


        if(url[1].contains("#")){
            //如果包含就按这个再拆分
           String player[] =  url[1].split("#");


            Message msg = new Message();
            msg.what = 31;

            Bundle bundle = new Bundle();
            bundle.putString("vod_play_url", vod_play_url);//发个通知告诉线程，这个是剧集需要列出来
            msg.setData(bundle);
            Thandler.sendMessage(msg);//用activity中的handler发送消息

            dram_hint.setVisibility(View.VISIBLE);

            return player[0];
        }

        dram_hint.setVisibility(View.GONE);
        return url[1];
    }


    //简介与评论的tab点击事件（虽然我做的是按钮）
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_detail:
                viewPager.setCurrentItem(0);
                break;
            case R.id.btn_discuss:
                viewPager.setCurrentItem(1);
                break;
        }
    }

    //充填和响应事件的
    private void initDetail() {

        //详情下拉
        iv_detail = (ImageView) palyerDetail.findViewById(R.id.iv_detail);
        tv_detail = (TextView) palyerDetail.findViewById(R.id.tv_detail);

        iv_detail.setOnClickListener(new View.OnClickListener() {
            boolean isShowDes = false;

            @Override
            public void onClick(View v) {
                //这是点击的代码
                if (isShowDes) {
                    tv_detail.setEllipsize(TextUtils.TruncateAt.END);//收起
                    tv_detail.setLines(1);
                    iv_detail.setImageDrawable(getResources().getDrawable(R.drawable.ic_pull_down));
                } else {
                    tv_detail.setEllipsize(null);//展开
                    tv_detail.setSingleLine(false);//这个方法是必须设置的，否则无法展开
                    iv_detail.setImageDrawable(getResources().getDrawable(R.drawable.ic_pull_up));
                }
                isShowDes = !isShowDes;
            }
        });

        tv_player_title = (TextView) palyerDetail.findViewById(R.id.tv_player_title);
        tv_player_time = (TextView) palyerDetail.findViewById(R.id.tv_player_time);

        ll_list= (LinearLayout) palyerDetail.findViewById(R.id.ll_list);
        hlv= (HorizontalListView) palyerDetail.findViewById(R.id.hlv);

        //剧集-更多
        dram_hint= (LinearLayout)palyerDetail. findViewById(R.id.dram_hint);
    }


}